package cn.wolfcode.util;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class ControllerExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public Object exceptionHandler (RuntimeException e, HttpServletResponse response, HandlerMethod handlerMethod)
            throws IOException {
        e.printStackTrace();
        //判断是否是ajax的方法,通过responsebody注解判断
        if (handlerMethod.hasMethodAnnotation(ResponseBody.class)) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(new JsonResult(false, "操作失败")));
            return null;
        } else {
            //如果是string类型的  就返回错误视图
            return "common/error";

        }
    }

    /**
     * 捕捉没有权限的异常
     * @param e
     * @param response
     * @param handlerMethod
     * @return
     * @throws IOException
     */
    @ExceptionHandler(UnauthorizedException.class)
    public Object HandlerUnauthenticated (RuntimeException e, HttpServletResponse response, HandlerMethod handlerMethod)
            throws IOException {
        e.printStackTrace();
        //判断是否是ajax的方法,通过responsebody注解判断
        if (handlerMethod.hasMethodAnnotation(ResponseBody.class)) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(new JsonResult(false, " 你没有权限操作")));
            return null;
        } else {
            //如果是string类型的就返回错误视图
            return "common/nopermission";

        }
    }
}
